package com.example.seabedmusic.utils;

import android.content.Context;
import android.content.SharedPreferences;
import com.example.seabedmusic.entity.Song;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class RecentPlayManager {
    private static final String PREF_NAME = "recent_play_prefs";
    private static final String KEY_RECENT_SONGS = "recent_songs";
    private static final int MAX_RECENT_SIZE = 20; // 最多保存20首

    private static RecentPlayManager instance;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    private RecentPlayManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    public static synchronized RecentPlayManager getInstance(Context context) {
        if (instance == null) {
            instance = new RecentPlayManager(context);
        }
        return instance;
    }

    /**
     * 添加歌曲到最近播放
     */
    public void addToRecent(Song song) {
        List<Song> recentSongs = getRecentSongs();

        // 移除已存在的相同歌曲（避免重复）
        for (int i = 0; i < recentSongs.size(); i++) {
            Song existing = recentSongs.get(i);
            if (existing.getTitle().equals(song.getTitle()) &&
                    existing.getArtist().equals(song.getArtist())) {
                recentSongs.remove(i);
                break;
            }
        }

        // 添加到开头
        recentSongs.add(0, song);

        // 如果超过最大数量，移除最老的
        if (recentSongs.size() > MAX_RECENT_SIZE) {
            recentSongs = recentSongs.subList(0, MAX_RECENT_SIZE);
        }

        saveRecentSongs(recentSongs);
    }

    /**
     * 获取最近播放列表
     */
    public List<Song> getRecentSongs() {
        String json = sharedPreferences.getString(KEY_RECENT_SONGS, null);
        if (json == null) {
            return new ArrayList<>();
        }

        try {
            Type type = new TypeToken<List<Song>>(){}.getType();
            List<Song> songs = gson.fromJson(json, type);
            return songs != null ? songs : new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 清空最近播放
     */
    public void clearRecentSongs() {
        sharedPreferences.edit().remove(KEY_RECENT_SONGS).apply();
    }

    private void saveRecentSongs(List<Song> songs) {
        String json = gson.toJson(songs);
        sharedPreferences.edit().putString(KEY_RECENT_SONGS, json).apply();
    }
}
